import React, { useState, useEffect } from 'react';
import {
  Card,
  Form,
  Input,
  Button,
  Upload,
  message,
  Space,
  Modal,
  Row,
  Col,
  Typography,
  Spin
} from 'antd';
import {
  SaveOutlined,
  EyeOutlined,
  SendOutlined,
  UploadOutlined,
  PictureOutlined,
  FileOutlined,
  DeleteOutlined,
  CloudUploadOutlined
} from '@ant-design/icons';
import { useNavigate, useSearchParams } from 'react-router-dom';
import FileViewer from 'react-file-viewer';
import { getToken } from '../../utils';
import AiEditorComponent from '../../components/AiEditorComponent';
import './CreateArticle.scss';

const { Title, Text } = Typography;

const CreateArticle = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const articleId = searchParams.get('id');
  const isEdit = !!articleId;

  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [publishing, setPublishing] = useState(false);
  const [content, setContent] = useState('');
  const [coverImage, setCoverImage] = useState(null);
  const [attachments, setAttachments] = useState([]);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewContent, setPreviewContent] = useState('');
  const editorRef = React.useRef(null);

  // 处理编辑器内容变化
  const handleContentChange = (newContent) => {
    setContent(newContent);
  };

  // 加载作品数据（编辑模式）
  useEffect(() => {
    if (isEdit) {
      loadArticle();
    }
  }, [articleId]);

  const loadArticle = async () => {
    try {
      setLoading(true);
      const response = await fetch(`http://211.86.197.10:9091/api/articles/${articleId}`);
      const result = await response.json();

      if (result.success) {
        const article = result.data;
        form.setFieldsValue({
          title: article.title
        });
        setContent(article.content_html || '');
        setCoverImage(article.cover_image);
        
        // 加载附件数据
        if (article.attachments && article.attachments.length > 0) {
          const formattedAttachments = article.attachments.map(attachment => ({
            id: attachment.id,
            name: attachment.original_name,
            url: attachment.file_url,
            type: attachment.mime_type,
            size: attachment.file_size,
            fileType: attachment.file_type
          }));
          setAttachments(formattedAttachments);
        }
      } else {
        message.error('加载作品失败');
        navigate('/');
      }
    } catch (error) {
      console.error('加载作品错误:', error);
      message.error('加载作品失败');
      navigate('/');
    } finally {
      setLoading(false);
    }
  };

  // 保存草稿
  const handleSaveDraft = async () => {
    try {
      const values = await form.validateFields(['title']);
      if (!content.trim()) {
        message.warning('请输入作品内容');
        return;
      }

      setSaving(true);
      const articleData = {
        title: values.title,
        content: { html: content }, // JSONB 格式的内容
        content_html: content,
        cover_image: coverImage,
        status: 'draft'
      };

      const url = isEdit ? `http://211.86.197.10:9091/api/articles/${articleId}` : 'http://211.86.197.10:9091/api/articles';
      const method = isEdit ? 'PUT' : 'POST';

      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${getToken()}`
        },
        body: JSON.stringify(articleData)
      });

      const result = await response.json();

      if (result.success) {
        const savedArticleId = result.data.id;
        
        // 如果是新建模式，保存临时附件到数据库
        if (!isEdit) {
          await saveTemporaryAttachments(savedArticleId);
          navigate(`/create?id=${savedArticleId}`);
        }
        
        message.success('草稿保存成功');
      } else {
        message.error(result.message || '保存失败');
      }
    } catch (error) {
      console.error('保存草稿错误:', error);
      message.error('保存失败');
    } finally {
      setSaving(false);
    }
  };

  // 预览作品
  const handlePreview = () => {
    const values = form.getFieldsValue();
    const previewHtml = `
      <div style="max-width: 800px; margin: 0 auto; padding: 20px;">
        <h1 style="text-align: center; margin-bottom: 20px;">${values.title || '未命名作品'}</h1>
        ${coverImage ? `<img src="${coverImage}" style="width: 100%; max-width: 600px; margin: 20px auto; display: block;" alt="封面图片" />` : ''}
        <div style="line-height: 1.6; font-size: 16px;">
          ${content || '<p>暂无内容</p>'}
        </div>
      </div>
    `;
    setPreviewContent(previewHtml);
    setPreviewVisible(true);
  };

  // 发布作品
  const handlePublish = async () => {
    try {
      const values = await form.validateFields();
      if (!content.trim()) {
        message.warning('请输入作品内容');
        return;
      }

      setPublishing(true);
      const articleData = {
        title: values.title,
        content: { html: content }, // JSONB 格式的内容
        content_html: content,
        cover_image: coverImage,
        status: 'published'
      };

      const url = isEdit ? `http://211.86.197.10:9091/api/articles/${articleId}` : 'http://211.86.197.10:9091/api/articles';
      const method = isEdit ? 'PUT' : 'POST';

      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${getToken()}`
        },
        body: JSON.stringify(articleData)
      });

      const result = await response.json();

      if (result.success) {
        const publishedArticleId = result.data.id;
        
        // 如果是新建模式，保存临时附件到数据库
        if (!isEdit) {
          await saveTemporaryAttachments(publishedArticleId);
        }
        
        message.success('作品发布成功');
        navigate('/');
      } else {
        message.error(result.message || '发布失败');
      }
    } catch (error) {
      console.error('发布作品错误:', error);
      message.error('发布失败');
    } finally {
      setPublishing(false);
    }
  };

  // 上传封面图片
  const handleCoverUpload = ({ file, onSuccess, onError }) => {
    const formData = new FormData();
    formData.append('file', file);

    fetch('http://211.86.197.10:9091/api/upload/image', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${getToken()}`
      },
      body: formData
    })
    .then(response => response.json())
    .then(result => {
      if (result.success) {
        setCoverImage(result.data.url);
        onSuccess();
        message.success('封面上传成功');
      } else {
        onError();
        message.error('封面上传失败');
      }
    })
    .catch(error => {
      console.error('上传错误:', error);
      onError();
      message.error('封面上传失败');
    });
  };

  // 上传附件
  const handleAttachmentUpload = async ({ file, onSuccess, onError }) => {
    try {
      console.log('开始上传附件:', file.name);
      
      // 1. 先上传文件
      const formData = new FormData();
      formData.append('file', file);

      const uploadResponse = await fetch('http://211.86.197.10:9091/api/upload/document', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${getToken()}`
        },
        body: formData
      });

      console.log('上传响应状态:', uploadResponse.status);
      
      if (!uploadResponse.ok) {
        throw new Error(`上传失败: ${uploadResponse.status} ${uploadResponse.statusText}`);
      }

      const uploadResult = await uploadResponse.json();
      console.log('上传结果:', uploadResult);
      
      if (!uploadResult.success) {
        throw new Error(uploadResult.message || '文件上传失败');
      }

      // 2. 如果是编辑模式且有作品ID，直接保存到数据库
      if (isEdit && articleId) {
        try {
          const attachmentData = {
            file_name: uploadResult.data.filename,
            original_name: uploadResult.data.originalName,
            file_type: getFileTypeFromMime(uploadResult.data.type),
            file_size: uploadResult.data.size,
            file_url: uploadResult.data.url,
            mime_type: uploadResult.data.type
          };

          const saveResponse = await fetch(`http://211.86.197.10:9091/api/articles/${articleId}/attachments`, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'Authorization': `Bearer ${getToken()}`
            },
            body: JSON.stringify(attachmentData)
          });

          const saveResult = await saveResponse.json();
          
          if (saveResult.success) {
            // 添加到本地状态，使用数据库返回的ID
            const newAttachment = {
              id: saveResult.data.id,
              name: saveResult.data.original_name,
              url: `http://211.86.197.10:9091${saveResult.data.file_url}`,
              type: saveResult.data.mime_type,
              size: saveResult.data.file_size,
              fileType: saveResult.data.file_type,
              original_name: saveResult.data.original_name,
              file_url: saveResult.data.file_url,
              mime_type: saveResult.data.mime_type,
              file_size: saveResult.data.file_size
            };
            
            setAttachments(prev => [...prev, newAttachment]);
            console.log('附件已保存到数据库:', saveResult.data.id);
          } else {
            throw new Error(saveResult.message || '保存附件到数据库失败');
          }
        } catch (saveError) {
          console.error('保存附件到数据库失败:', saveError);
          // 如果保存失败，仍然添加到本地状态作为临时文件
          const newAttachment = {
            id: Date.now(),
            name: uploadResult.data.originalName,
            url: `http://211.86.197.10:9091${uploadResult.data.url}`,
            type: uploadResult.data.type,
            size: uploadResult.data.size,
            fileType: getFileTypeFromMime(uploadResult.data.type),
            isTemporary: true
          };
          
          setAttachments(prev => [...prev, newAttachment]);
          message.warning('附件上传成功，但保存到数据库失败，发布时会重新尝试');
        }
      } else {
        // 新建模式，添加到本地状态作为临时文件
        const newAttachment = {
          id: Date.now(),
          name: uploadResult.data.originalName,
          url: `http://211.86.197.10:9091${uploadResult.data.url}`,
          type: uploadResult.data.type,
          size: uploadResult.data.size,
          fileType: getFileTypeFromMime(uploadResult.data.type),
          isTemporary: true,
          // 保存原始数据用于后续保存
          uploadData: {
            file_name: uploadResult.data.filename,
            original_name: uploadResult.data.originalName,
            file_type: getFileTypeFromMime(uploadResult.data.type),
            file_size: uploadResult.data.size,
            file_url: uploadResult.data.url,
            mime_type: uploadResult.data.type
          }
        };
        
        setAttachments(prev => [...prev, newAttachment]);
      }
      
      onSuccess();
      message.success('附件上传成功');
      
    } catch (error) {
      console.error('上传错误:', error);
      onError();
      message.error(error.message || '附件上传失败');
    }
  };

  // 根据MIME类型获取文件类型
  const getFileTypeFromMime = (mimeType) => {
    if (mimeType.includes('image')) return 'image';
    if (mimeType.includes('video')) return 'video';
    return 'document';
  };

  // 保存临时附件到数据库
  const saveTemporaryAttachments = async (articleId) => {
    const temporaryAttachments = attachments.filter(att => att.isTemporary && att.uploadData);
    
    if (temporaryAttachments.length === 0) {
      return;
    }

    console.log('保存临时附件到数据库:', temporaryAttachments.length, '个文件');

    for (const attachment of temporaryAttachments) {
      try {
        const response = await fetch(`http://211.86.197.10:9091/api/articles/${articleId}/attachments`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${getToken()}`
          },
          body: JSON.stringify(attachment.uploadData)
        });

        const result = await response.json();
        
        if (result.success) {
          console.log('附件保存成功:', attachment.name);
          // 更新本地状态，移除临时标记
          setAttachments(prev => prev.map(att => 
            att.id === attachment.id 
              ? { ...att, id: result.data.id, isTemporary: false }
              : att
          ));
        } else {
          console.error('附件保存失败:', attachment.name, result.message);
        }
      } catch (error) {
        console.error('保存附件错误:', attachment.name, error);
      }
    }
  };

  // 删除附件
  const handleDeleteAttachment = async (attachmentId) => {
    try {
      console.log('删除附件:', attachmentId);
      
      // 暂时只处理本地状态，避免API问题
      // TODO: 后续需要调用API删除数据库中的附件
      
      // 从本地状态中移除
      setAttachments(prev => prev.filter(item => item.id !== attachmentId));
      message.success('附件删除成功');
    } catch (error) {
      console.error('删除附件错误:', error);
      message.error('删除附件失败');
    }
  };

  // 预览附件
  const handlePreviewAttachment = async (attachment) => {
    const fileName = attachment.name;
    const fileType = attachment.type;
    
    // 检查是否是可转换的文档
    const isConvertibleDocument = [
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      'application/msword',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'application/vnd.ms-excel',
      'application/vnd.openxmlformats-officedocument.presentationml.presentation',
      'application/vnd.ms-powerpoint',
      'text/plain'
    ].includes(fileType);

    // 如果是可转换的文档且有ID（已保存到数据库），尝试转换预览
    if (isConvertibleDocument && attachment.id && !attachment.isTemporary) {
      try {
        const response = await fetch(`http://211.86.197.10:9091/api/documents/${attachment.id}/convert`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${getToken()}`
          }
        });

        const result = await response.json();

        if (result.success) {
          Modal.info({
            title: `预览: ${fileName}`,
            width: '90%',
            style: { top: 20 },
            className: 'document-preview-modal',
            content: (
              <div style={{ 
                maxHeight: '70vh', 
                overflow: 'auto',
                border: '1px solid #d9d9d9',
                borderRadius: '6px',
                backgroundColor: '#fff'
              }}>
                <div 
                  dangerouslySetInnerHTML={{ __html: result.data.html }}
                  style={{ padding: '16px' }}
                />
              </div>
            ),
            footer: (
              <div style={{ textAlign: 'center' }}>
                <Space>
                  <Button 
                    type="primary" 
                    onClick={() => window.open(attachment.url, '_blank')}
                  >
                    在新窗口打开原文件
                  </Button>
                  <Button 
                    onClick={() => {
                      const link = document.createElement('a');
                      link.href = attachment.url;
                      link.download = attachment.name;
                      document.body.appendChild(link);
                      link.click();
                      document.body.removeChild(link);
                    }}
                  >
                    下载原文件
                  </Button>
                </Space>
              </div>
            )
          });
          return;
        }
      } catch (error) {
        console.error('文档转换失败:', error);
      }
    }

    // 根据文件类型和扩展名确定预览方式
    const getFileType = (fileName, mimeType) => {
      const extension = fileName.toLowerCase().split('.').pop();
      
      // 根据扩展名判断
      if (extension === 'pdf') return 'pdf';
      if (['doc', 'docx'].includes(extension)) return 'docx';
      if (['ppt', 'pptx'].includes(extension)) return 'pptx';
      if (['xls', 'xlsx'].includes(extension)) return 'xlsx';
      if (['txt'].includes(extension)) return 'txt';
      
      // 根据MIME类型判断
      if (fileType) {
        if (fileType.includes('pdf')) return 'pdf';
        if (fileType.includes('word') || fileType.includes('document')) return 'docx';
        if (fileType.includes('presentation') || fileType.includes('powerpoint')) return 'pptx';
        if (fileType.includes('sheet') || fileType.includes('excel')) return 'xlsx';
        if (fileType.includes('text')) return 'txt';
      }
      
      return 'pdf'; // 默认
    };

    const viewerFileType = getFileType(attachment.name, attachment.type);
    
    Modal.info({
      title: `预览: ${attachment.name}`,
      width: '90%',
      style: { top: 20 },
      className: 'preview-modal',
      content: (
        <div className="file-viewer-container">
          <FileViewer
            fileType={viewerFileType}
            filePath={attachment.url}
            onError={(error) => {
              console.error('文件预览错误:', error);
              message.error('文件预览失败，可能是文件格式不支持或网络连接问题');
            }}
          />
        </div>
      ),
      footer: (
        <div style={{ textAlign: 'center' }}>
          <Space>
            <Button 
              type="primary" 
              onClick={() => window.open(attachment.url, '_blank')}
            >
              在新窗口打开
            </Button>
            <Button 
              onClick={() => {
                const link = document.createElement('a');
                link.href = attachment.url;
                link.download = attachment.name;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
              }}
            >
              下载文件
            </Button>
          </Space>
        </div>
      )
    });
  };

  if (loading) {
    return (
      <div className="loading-container">
        <Spin size="large" />
        <div className="loading-text">加载中...</div>
      </div>
    );
  }

  return (
    <div className="create-article-container">
      <Card>
        <Form form={form} layout="vertical">
          <Form.Item
            name="title"
            label={<span style={{ fontSize: '16px', fontWeight: 600 }}>作品标题</span>}
            rules={[{ required: true, message: '请输入作品标题' }]}
          >
            <Input 
              placeholder="请输入作品标题" 
              size="large"
              style={{ fontSize: '18px', fontWeight: 500 }}
            />
          </Form.Item>

          <Form.Item label={<span style={{ fontSize: '16px', fontWeight: 600 }}>作品内容</span>}>
            <AiEditorComponent
              ref={editorRef}
              value={content}
              onChange={handleContentChange}
              placeholder="开始写作你的精彩内容..."
              height="500px"
            />
          </Form.Item>

          {/* 操作按钮区域 - 放在富文本编辑器下方 */}
          <div className="action-buttons">
            <Row gutter={[16, 16]}>
              <Col xs={24} sm={12} md={6}>
                <Upload
                  customRequest={handleCoverUpload}
                  showUploadList={false}
                  accept="image/*"
                >
                  <Button 
                    icon={<PictureOutlined />} 
                    block
                    type={coverImage ? "default" : "dashed"}
                  >
                    {coverImage ? '更换封面' : '上传封面'}
                  </Button>
                </Upload>
              </Col>

              <Col xs={24} sm={12} md={6}>
                <Button 
                  icon={<SaveOutlined />} 
                  onClick={handleSaveDraft}
                  loading={saving}
                  block
                >
                  保存草稿
                </Button>
              </Col>

              <Col xs={24} sm={12} md={6}>
                <Button 
                  icon={<EyeOutlined />} 
                  onClick={handlePreview}
                  block
                >
                  预览
                </Button>
              </Col>

              <Col xs={24} sm={12} md={6}>
                <Button 
                  type="primary"
                  icon={<SendOutlined />} 
                  onClick={handlePublish}
                  loading={publishing}
                  block
                >
                  发布作品
                </Button>
              </Col>
            </Row>
          </div>

          {/* 封面预览 */}
          {coverImage && (
            <div className="cover-preview">
              <Text strong style={{ fontSize: '14px' }}>封面预览:</Text>
              <div style={{ marginTop: 12 }}>
                <img 
                  src={coverImage} 
                  alt="封面预览" 
                  className="cover-image"
                />
                <div style={{ marginTop: 12 }}>
                  <Button 
                    type="link" 
                    size="small" 
                    danger
                    onClick={() => setCoverImage(null)}
                  >
                    删除封面
                  </Button>
                </div>
              </div>
            </div>
          )}

          {/* 附件上传区域 */}
          <div className="attachments-section">
            <Title level={4} className="section-title">
              <CloudUploadOutlined style={{ marginRight: 8 }} />
              附件管理
            </Title>
            
            <div className="upload-area">
              <Upload
                customRequest={handleAttachmentUpload}
                showUploadList={false}
                accept=".pdf,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.txt"
                multiple
              >
                <Button 
                  icon={<UploadOutlined />}
                  size="large"
                >
                  上传附件 (支持 PDF, Word, PPT, Excel, TXT)
                </Button>
              </Upload>
              <div style={{ marginTop: 8, color: '#8c8c8c', fontSize: '12px' }}>
                支持多文件上传，单个文件最大 50MB
              </div>
            </div>

            {attachments.length > 0 && (
              <div className="attachment-list">
                <Text strong style={{ fontSize: '14px', marginBottom: 12, display: 'block' }}>
                  已上传附件 ({attachments.length}):
                </Text>
                {attachments.map(attachment => (
                  <Card 
                    key={attachment.id} 
                    size="small" 
                    className="attachment-item"
                  >
                    <Row align="middle" justify="space-between">
                      <Col flex="auto">
                        <Space>
                          <FileOutlined style={{ fontSize: '16px', color: '#1890ff' }} />
                          <div className="attachment-info">
                            <div className="attachment-name">{attachment.name}</div>
                            <div className="attachment-size">
                              {(attachment.size / 1024 / 1024).toFixed(2)} MB
                            </div>
                          </div>
                        </Space>
                      </Col>
                      <Col>
                        <Space className="attachment-actions">
                          <Button 
                            type="link" 
                            size="small"
                            onClick={() => handlePreviewAttachment(attachment)}
                          >
                            预览
                          </Button>
                          <Button 
                            type="link" 
                            size="small"
                            onClick={() => window.open(attachment.url, '_blank')}
                          >
                            下载
                          </Button>
                          <Button 
                            type="link" 
                            size="small" 
                            danger
                            icon={<DeleteOutlined />}
                            onClick={() => handleDeleteAttachment(attachment.id)}
                          >
                            删除
                          </Button>
                        </Space>
                      </Col>
                    </Row>
                  </Card>
                ))}
              </div>
            )}
          </div>
        </Form>
      </Card>

      {/* 预览模态框 */}
      <Modal
        title="作品预览"
        open={previewVisible}
        onCancel={() => setPreviewVisible(false)}
        footer={null}
        width="90%"
        style={{ top: 20 }}
        className="preview-modal"
      >
        <div 
          className="preview-content"
          dangerouslySetInnerHTML={{ __html: previewContent }}
        />
      </Modal>
    </div>
  );
};

export default CreateArticle;